package com.whk.aspect;

import com.alibaba.fastjson.JSONObject;
import com.whk.mapper.OperateLogMapper;
import com.whk.pojo.OperateLog;
import com.whk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 日志切面类：将日志存储到数据库
 */
@Aspect
@Component
@Slf4j
public class AspectLog {
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired//获得前端请求实例
    private HttpServletRequest httpServletRequest;

    //将日志存进数据库
    @Around("@annotation(com.whk.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        //获得jwt令牌
        String jwt = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);


        //获得该员工id
        Integer id = (Integer) claims.get("id");

        //获得操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        //获得操作的类名
        String className = joinPoint.getTarget().getClass().getName();

        //获得操作方法名
        String methodName = joinPoint.getSignature().getName();

        //获得方法参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);

        //执行方法前的时间戳·
        long begin = System.currentTimeMillis();

        //调用原始方法
        Object result = joinPoint.proceed();

        //执行方法后的时间戳·
        long end = System.currentTimeMillis();

        //获得方法返回值
        String returnValue = JSONObject.toJSONString(result);

        //获得执行方法的执行时间
        long costTime = end - begin;


        OperateLog operateLog = new OperateLog(null, id, operateTime, className, methodName, methodParams, returnValue, costTime);
        //插入操作日志数据
        operateLogMapper.insert(operateLog);

        log.info("插入日志数据：{}", operateLog);


        return result;
    }
}
